package com.dotstone.chipism.util;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.DeviceType;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.widget.Toast;

/*************************************************************************
 * 公 司： 深圳市高金科技有限公司 作 者： 深圳市高金科技有限公司 文件名称：Util.java 内容摘要：工具类 日 期： 2016-11-28
 ************************************************************************/
public class Util {

	private Context c;

	public void setContext(Context c) {
		this.c = c;
	}

	public int getStatusBarHeight(Context c) {
		int result = 0;
		int resourceId = c.getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = c.getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	public static boolean isLogin(Context c) {
		if (SPUtils.get(c, "token", "").equals("")) {
			return false;
		}

		return true;
	}

	public static boolean isAddUniversalRemote(Context c) {
		if (SPUtils.get(c, "universalfan", "").equals("")) {
			return false;
		}
		return true;
	}

	/**
	 * 校验手机号
	 * 
	 * @param mobile
	 * @return 校验通过返回true，否则返回false
	 */
	public static boolean isMobile(String mobile) {
		return Pattern.matches("^((17[0-9])(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$", mobile);
	}

	/**
	 * 校验邮箱
	 * 
	 * @param email
	 * @return 校验通过返回true，否则返回false
	 */
	public static boolean isEmail(String email) {
		return Pattern.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$",
				email);
	}

	public static String getAppliance(Context c, int type) {
		String appliance = "";
		switch (type) {
		case DeviceType.DEVICE_TYPE_TV:
			appliance = c.getString(R.string.yaokong_add_tv);
			break;
		case DeviceType.DEVICE_TYPE_AIR_CONTROLLER:
			appliance = c.getString(R.string.yaokong_add_kongtiao);
			break;
		case DeviceType.DEVICE_TYPE_FAN:
			appliance = c.getString(R.string.yaokong_add_fenshan);
			break;
		case DeviceType.DEVICE_TYPE_PROJECTOR:
			appliance = c.getString(R.string.yaokong_add_touyingyi);
			break;
		case DeviceType.DEVICE_TYPE_SATELLITE:
			appliance = c.getString(R.string.yaokong_add_jidinghe);
			break;
		case DeviceType.DEVICE_TYPE_DVD:
			appliance = c.getString(R.string.yaokong_add_dvd);
			break;
		case DeviceType.DEVICE_TYPE_CAMERA:
			appliance = c.getString(R.string.yaokong_add_xaingji);
			break;
		case DeviceType.DEVICE_TYPE_DENG:
			appliance = c.getString(R.string.yaokong_add_deng);
			break;
		case DeviceType.DEVICE_TYPE_AUDIO:
			appliance = c.getString(R.string.yaokong_add_gongfang);
			break;
		case DeviceType.DEVICE_TYPE_IPTV:
			appliance = c.getString(R.string.yaokong_add_iptv);
			break;
		case DeviceType.DEVICE_TYPE_BOX:
			appliance = c.getString(R.string.yaokong_add_hezi);
			break;
		// case DeviceType.DEVICE_TYPE_BOX2:
		// appliance = c.getString(R.string.yaokong_add_hezi);
		// break;
		default:
			break;
		}
		return appliance;
	}

	public static String getTitle(Context c, String name, int type) {
		String title = "";
		switch (type) {
		case DeviceType.DEVICE_TYPE_AIR_CONTROLLER:
			title = c.getString(R.string.yaokong_add_kongtiao1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_AUDIO:
			title = c.getString(R.string.yaokong_add_gongfang1) + ":" + name;
			break;
		// case DeviceType.DEVICE_TYPE_BOX:
		// title = c.getString(R.string.yaokong_add_hezi1) + ":" + name;
		// break;
		case DeviceType.DEVICE_TYPE_CAMERA:
			title = c.getString(R.string.yaokong_add_xaingji1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_DIY_REMOTE:
			title = c.getString(R.string.yaokong_add_diy1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_DVD:
			title = c.getString(R.string.yaokong_add_dvd1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_FAN:
			title = c.getString(R.string.yaokong_add_fenshan1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_PROJECTOR:
			title = c.getString(R.string.yaokong_add_touyingyi1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_REMOTE_LIGHT:
			title = c.getString(R.string.yaokong_add_rgbdeng1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_REMOTE_SOCKET:
			title = c.getString(R.string.yaokong_add_chazuo1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_RGB_LIGHT:
			title = c.getString(R.string.yaokong_add_rgbdeng1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_RGB_TIAO:
			title = c.getString(R.string.yaokong_add_rgbdeng2) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_SATELLITE:
			title = c.getString(R.string.yaokong_add_jidinghe1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_SOCKET:
			title = c.getString(R.string.yaokong_add_chazuo1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_SW_LIGHT:
			title = c.getString(R.string.yaokong_add_cwdeng1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_THREE_WITCH:
			title = c.getString(R.string.yaokong_add_three_switch) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_TV:
			title = c.getString(R.string.yaokong_add_tv1) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_UNIVERSALY_INFLARED_LIGHT:
			title = c.getString(R.string.yaokong_add_universal_light) + ":" + name;
			break;
		case DeviceType.DEVICE_TYPE_WLAN:
			title = c.getString(R.string.yaokong_add_wlan) + ":" + name;
			break;
		// case DeviceType.DEVICE_TYPE_WLAN2:
		// title = c.getString(R.string.yaokong_add_wlan2) + ":" + name;
		// break;
		default:
			break;
		}
		return title;

	}

	public static HashMap<Integer, String> getKeyMap(final String deviceId) {
		final HashMap<Integer, String> mKvMap = new HashMap<Integer, String>();

		final String mDeviceJsonStr = DeviceManager.getInstance().getmJsonStr();
		if (mDeviceJsonStr != null && deviceId != null) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					JSONObject jsonObject;
					JSONArray keyInfo = null;
					try {
						jsonObject = new JSONObject(mDeviceJsonStr);
						JSONArray data = jsonObject.getJSONArray("data");
						for (int i = 0; i < data.length(); i++) {
							JSONObject deviceInfo = data.getJSONObject(i).getJSONObject("deviceInfo");
							keyInfo = data.getJSONObject(i).optJSONArray("deviceButton");
							String deviceId1 = deviceInfo.getString("deviceId");
							Log.i("Tag", "遥控器界面获取设备ID" + deviceId1);
							if (deviceId1.equals(deviceId)) {
								Log.i("Tag", "符合条件的设备信息" + deviceInfo.toString());
								break;
							}
						}
						if (keyInfo != null) {
							Log.i("Tag", "keyInfo不为空");
							for (int i = 0; i < keyInfo.length(); i++) {
								JSONObject key = keyInfo.getJSONObject(i);
								String codeValue = key.optString("buttonCmd");
								int position = key.optInt("position");
								if (key != null) {
									mKvMap.put(position, codeValue);
								}
							}
						}
						Log.i("Tag", "get " + mKvMap.size() + "kv");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}).start();
		}
		return mKvMap;
	}

	// private static RotateAnimation rotate2;
	// private static Dialog dialog;
	private static String currentPackageName;
	private static ActivityManager am;
	private static ComponentName cn;

	public static boolean isRunningForeground(Context context) {
		am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		cn = am.getRunningTasks(1).get(0).topActivity;
		currentPackageName = cn.getPackageName();
		// Log.i("wmy", "currentPackageName" + " "+currentPackageName);
		if (!TextUtils.isEmpty(currentPackageName) && (currentPackageName.equals("com.dotstone.chipism"))) {
			// Log.i("wmy", "true");
			return true;
		}
		// Log.i("wmy", "false");
		return false;
	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	// public static String md5Password(String password) {
	//
	// try {
	// // 得到一个信息摘要器
	// MessageDigest digest = MessageDigest.getInstance("md5");
	// byte[] result = digest.digest(password.getBytes());
	// StringBuffer buffer = new StringBuffer();
	// // 把没一个byte 做一个与运算 0xff;
	// for (byte b : result) {
	// // 与运算
	// int number = b & 0xff;// 加盐
	// String str = Integer.toHexString(number);
	// if (str.length() == 1) {
	// buffer.append("0");
	// }
	// buffer.append(str);
	// }
	//
	// // 标准的md5加密后的结果
	// return buffer.toString();
	// } catch (NoSuchAlgorithmException e) {
	// e.printStackTrace();
	// return "";
	// }
	//
	// }

	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	public static int Dp2Px(Context context, float dp) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dp * scale + 0.5f);
	}

	public static int Px2Dp(Context context, float px) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (px / scale + 0.5f);
	}

	public static boolean isValue(Context c, String value) {
		if (value.equals("100")) {
			return true;
		} else if (value.equals("102")) {
			toast(c, R.string.email_has_been_registered);
		} else if (value.equals("103")) {
			toast(c, R.string.username_has_been_registered);
		} else if (value.equals("104")) {
			toast(c, R.string.username_does_not_comfirm_specification);
		} else if (value.equals("105")) {
			toast(c, R.string.email_does_not_comfirm_specification);
		} else if (value.equals("106")) {
			toast(c, R.string.pwd_must_include_6_12);
		} else if (value.equals("107")) {
			toast(c, R.string.pwd_cannot_only_letters);
		} else if (value.equals("108")) {
			toast(c, R.string.pwd_cannot_only_numbers);
		} else if (value.equals("109")) {
			toast(c, R.string.pwd_cannot_only_characters);
		} else if (value.equals("110")) {
			toast(c, R.string.incorrect_username_or_pwd);
		} else if (value.equals("111")) {
			toast(c, R.string.incorrect_old_pwd);
		} else if (value.equals("112")) {
			toast(c, R.string.user_not_exist);
		} else if (value.equals("113")) {
			toast(c, R.string.pwd_retrieval_has_exhausted_today);
		} else if (value.equals("114")) {
			toast(c, R.string.incorrect_email);
		} else if (value.equals("117")) {
			toast(c, R.string.file_type_error);
		} else if (value.equals("118")) {
			toast(c, R.string.file_larger_than_500kb);
		} else if (value.equals("119")) {
			toast(c, R.string.deviceexisted);
		} else if (value.equals("301")) {
			toast(c, R.string.request_too_often);
		} else if (value.equals("302")) {
			toast(c, R.string.request_too_often);
		} else if (value.equals("303")) {
			toast(c, R.string.request_too_often);
		} else if (value.equals("401")) {
			toast(c, R.string.system_exception);
		}
		return false;
	}

	public static void toast(final Context c, final int resId) {
		((Activity) c).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Toast.makeText(c, resId, Toast.LENGTH_SHORT).show();
			}
		});
	}

	// public static void clossProgressDialog(ProgressDialog progressDialog) {
	// if (progressDialog != null) {
	// progressDialog.dismiss();
	// }
	// if (dialog != null) {
	// dialog.dismiss();
	// }
	// }

	public static Bitmap readBitMap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// ��ȡ��ԴͼƬ
		InputStream is = context.getResources().openRawResource(resId);
		return BitmapFactory.decodeStream(is, null, opt);
	}

	public static String transCmd(int cmd, int src, int dest, int dir, String deviceId, int requestTime, int data[],
			String userId) {
		String sendStr = "";
		JSONObject jo = new JSONObject();
		try {
			jo.put("cmd", cmd);
			jo.put("src", src);
			jo.put("dest", dest);
			jo.put("dir", dir);
			jo.put("deviceId", deviceId);
			jo.put("requestTime", requestTime);
			if (data != null && data.length != 0) {
				jo.put("data", data);
			}
			if (userId != null && userId != "") {
				jo.put("userId", userId);
			}
			sendStr = jo.toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sendStr;
	}

	public static String transTime(long timeStamp) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(timeStamp);
		return time;
	}

	public static String transCmd1(int cmd, int src, int dest, int dir, String deviceId, int requestTime, String data,
			String userId, JSONObject jsonObject) {
		String sendStr = "";
		JSONObject jo = new JSONObject();
		try {

			jo.put("cmd", cmd);
			jo.put("src", src);
			jo.put("dest", dest);
			jo.put("dir", dir);
			jo.put("deviceId", deviceId);
			jo.put("requestTime", requestTime);
			jo.put("data", jsonObject);
			if (data != null && data != "") {
				jo.put("data", data);
			}
			if (userId != null && userId != "") {
				jo.put("userId", userId);
			}
			sendStr = jo.toString();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sendStr;
	}

	public static String getMac(String data) {
		String mac = "";
		try {
			JSONObject jo = new JSONObject(data);
			JSONObject jsonObject;
			JSONArray ja = jo.optJSONArray("msg");
			if (ja != null) {
				jsonObject = ja.getJSONObject(0);
				mac = jsonObject.getString("mac");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return mac;
	}

	public static int[] getTempRes(int temp) {
		int[] temps = new int[2];
		switch (temp) {
		case 16:
			temps[0] = R.drawable.ac_1;
			temps[1] = R.drawable.ac_6;
			break;
		case 17:
			temps[0] = R.drawable.ac_1;
			temps[1] = R.drawable.ac_7;
			break;
		case 18:
			temps[0] = R.drawable.ac_1;
			temps[1] = R.drawable.ac_8;
			break;
		case 19:
			temps[0] = R.drawable.ac_1;
			temps[1] = R.drawable.ac_9;
			break;
		case 20:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_0;
			break;
		case 21:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_1;
			break;
		case 22:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_2;
			break;
		case 23:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_3;
			break;
		case 24:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_4;
			break;
		case 25:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_5;
			break;
		case 26:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_6;
			break;
		case 27:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_7;
			break;
		case 28:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_8;
			break;
		case 29:
			temps[0] = R.drawable.ac_2;
			temps[1] = R.drawable.ac_9;
			break;
		case 30:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_0;
			break;
		case 31:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_1;
			break;
		case 32:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_2;
			break;
		case 33:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_3;
			break;
		case 34:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_4;
			break;
		case 35:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_5;
			break;
		case 36:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_6;
			break;
		case 37:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_7;
			break;
		case 38:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_8;
			break;
		case 39:
			temps[0] = R.drawable.ac_3;
			temps[1] = R.drawable.ac_9;
			break;
		case 40:
			temps[0] = R.drawable.ac_4;
			temps[1] = R.drawable.ac_0;
			break;

		default:
			break;
		}
		return temps;
	}

	public static String getHardDeviceVersion(String data) {
		String version = "";
		try {
			JSONObject jo = new JSONObject(data);
			JSONObject jsonObject;
			JSONArray ja = jo.getJSONArray("msg");
			if (ja != null) {
				jsonObject = ja.getJSONObject(0);
				version = jsonObject.getString("version");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return version;
	}

	public static int[] byte2HexStr(byte[] b) {
		int[] cmd = new int[b.length];
		String stmp = "";
		StringBuilder sb = new StringBuilder("");
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			sb.append((stmp.length() == 1) ? stmp : stmp);
			sb.append(",");
			cmd[n - 0] = Integer.parseInt(stmp, 16);
		}
		return cmd;
	}

	public static int[] byte2HexStr1(byte[] b) {
		int[] cmd = new int[b.length];
		String stmp = "";
		StringBuilder sb = new StringBuilder("");
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0xFF);
			sb.append((stmp.length() == 1) ? stmp : stmp);
			sb.append(",");
			cmd[n] = Integer.parseInt(stmp, 16);
			// System.out.println("cmd" + n + ":" + cmd[n]);
		}
		return cmd;
	}

	public static String getInstallTime(long installerTime) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		long time1 = Long.parseLong(installerTime + "");
		String d = format.format(time1);
		Date date = new Date();
		try {
			date = format.parse(d);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return d;

	}

	public static int getNavigationBarHeight(Context c) {
		Resources resources = c.getResources();
		int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
		// 获取NavigationBar的高度
		int height = resources.getDimensionPixelSize(resourceId);
		return height;
	}

	public static boolean getNavigationBarShow(Activity activity) {
		int dpi = 0;
		Display display = activity.getWindowManager().getDefaultDisplay();
		int h = display.getHeight();
		DisplayMetrics dm = new DisplayMetrics();
		@SuppressWarnings("rawtypes")
		Class c;
		try {
			c = Class.forName("android.view.Display");
			@SuppressWarnings("unchecked")
			Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
			method.invoke(display, dm);
			dpi = dm.heightPixels;
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (dpi > h) {
			return true;
		} else {
			return false;
		}
	}

	public static int getDpi(Activity activity) {
		int dpi = 0;
		Display display = activity.getWindowManager().getDefaultDisplay();
		DisplayMetrics dm = new DisplayMetrics();
		@SuppressWarnings("rawtypes")
		Class c;
		try {
			c = Class.forName("android.view.Display");
			@SuppressWarnings("unchecked")
			Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
			method.invoke(display, dm);
			dpi = dm.heightPixels;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dpi;
	}

	public static int getVersionCode(String version) {
		if (version.contains(".") && version.indexOf(".") < version.length() && version.indexOf(".") > 1
				&& version.length() > 1) {
			String versionStrs = version.substring(1, version.indexOf("."));
			return Integer.parseInt(versionStrs);
		} else {
			return 0;
		}

	}
	
	public static List<String> checkNull() {
		List<Device> devices = DeviceManager.getInstance().getNoWlansDevice();
		List<Device> wlans = DeviceManager.getInstance().getWlans();
		List<String> nullMids = new ArrayList<String>();
		List<String> mids = new ArrayList<String>();
		for (int i = 0; i < devices.size(); i++) {
			boolean e = false;
			for (String mid : mids) {
				if (mid.equals(devices.get(i).getMainDeviceId())) {
					e = true;
				}
			}
			if (!e) {
				mids.add(devices.get(i).getMainDeviceId());
			}
		}
		for (int i = 0; i < mids.size(); i++) {
			boolean e = false;
			for (Device wlan : wlans) {
				if (wlan.getDeviceID().equals(mids.get(i))) {
					e = true;
				}
			}
			if (!e) {
				nullMids.add(mids.get(i));
			}
		}
		return nullMids;

	}
}
